import dayjs from 'dayjs';

/**
 * @description 处理首字母大写 abc => Abc
 * @param str
 */
export const changeStr = (str: string) => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

/**
 * @description 随机生成颜色
 * @param {string} type
 * @return {string}
 */
export const randomColor = (type: 'rgb' | 'hex' | 'hsl'): string => {
  switch (type) {
    case 'rgb':
      return window.crypto.getRandomValues(new Uint8Array(3)).toString();
    case 'hex':
      return `#${Math.floor(Math.random() * 0xffffff)
        .toString(16)
        .padStart(6, `${Math.random() * 10}`)}`;
    case 'hsl':
      // 在25-95%范围内具有饱和度，在85-95%范围内具有亮度
      return [360 * Math.random(), `${100 * Math.random()}%`, `${100 * Math.random()}%`].toString();
  }
};

/**
 * 复制文本
 * @param text
 */
export const copyText = (text: string) => {
  return new Promise((resolve) => {
    const copyInput = document.createElement('input'); //创建一个input框获取需要复制的文本内容
    copyInput.value = text;
    document.body.appendChild(copyInput);
    copyInput.select();
    document.execCommand('copy');
    copyInput.remove();
    resolve(true);
  });
};

/**
 * @description 判断字符串是否是base64
 * @param {string} str
 */
export const isBase64 = (str: string): boolean => {
  if (str === '' || str.trim() === '') {
    return false;
  }
  try {
    return btoa(atob(str)) == str;
  } catch (err) {
    return false;
  }
};
// 对象转JSON
export const toJSON = (obj) => {
  return JSON.stringify(obj, (_, value) => {
    switch (true) {
      case typeof value === 'undefined':
        return 'undefined';
      case typeof value === 'symbol':
        return value.toString();
      case typeof value === 'function':
        return value.toString();
      default:
        break;
    }
    return value;
  });
};

/***
 * @description 是否是生产环境
 */
export const IS_PROD = import.meta.env.PROD;
export const IS_DEV = import.meta.env.DEV;

/***
 * @description 格式化日期
 * @param time
 */
export const formatDate = (time) => dayjs(time).format('YYYY-MM-DD HH:mm:ss');

/**
 *  @description 将一维数组转成树形结构数据
 * @param items
 * @param id
 * @param link
 */
export const generateTree = (items, id = 0, link = 'parent') => {
  return items
    .filter((item) => item[link] == id)
    .map((item) => ({
      ...item,
      slots: { title: 'name' },
      children: generateTree(items, item.departmentid),
    }));
};

/***
 * @description 原生加密明文
 * @param {string} plaintext
 */
// const encryption = (plaintext: string) =>
//   isBase64(plaintext) ? plaintext : window.btoa(window.encodeURIComponent(plaintext));

/**
 * @description 原生解密
 * @param {string} ciphertext
 */
// const decryption = (ciphertext: string) =>
//   isBase64(ciphertext) ? window.decodeURIComponent(window.atob(ciphertext)) : ciphertext;

// const viewsModules = import.meta.glob('../views/**/*.vue');

// /**
//  *
//  * @param {string} viewPath 页面的路径 `@/view/${viewPath}`
//  * @param {string} viewFileName  页面文件 默认 index.vue
//  */
// export const getAsyncPage = (viewPath: string, viewFileName = 'index') => {
//   if (viewPath.endsWith('.vue')) {
//     const p = `../views/${viewPath}`;
//     const pathKey = Object.keys(viewsModules).find((key) => key === p)!;
//     // console.log('viewsModules[pathKey]', viewsModules[pathKey]);
//     return viewsModules[pathKey];
//   } else {
//     const p = `../views/${viewPath}/${viewFileName}.vue`;
//     const pathKey = Object.keys(viewsModules).find((key) => key === p)!;
//     // console.log('viewsModules[pathKey]', viewsModules[pathKey]);
//     return viewsModules[pathKey];
//     // return () => import(/* @vite-ignore */ `../views/${viewPath}/${viewFileName}.vue`);
//   }
// };

/**
 * / _ - 转换成驼峰并将view替换成空字符串
 * @param {*} name name
 */
export const toHump = (name) => {
  return name
    .replace(/[-/_](\w)/g, (_, letter) => {
      return letter.toUpperCase();
    })
    .replace('views', '');
};

/** 模拟异步请求，实用性不高，主要用于demo模拟请求 */
export const waitTime = <T>(time = 100, data: any = true): Promise<T> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(data);
    }, time);
  });
};

/** 判断手机号码是否有效 */
export const isPhoneNumberValid = (phoneNumber: string) => {
  var regExp = /^1[3456789]\d{9}$/;
  if (regExp.test(phoneNumber)) {
    return true; // 返回true表示手机号码有效
  } else {
    return false; // 返回false表示手机号码无效
  }
};

/** 判断身份证号码是否有效 */
export const isChinaIDCard = (str: string) => {
  var chinaIDCardRegExp = /^[1-9]\d{5}(19|20)\d{2}(0\d|1[0-2])([012]\d|3[01])\d{3}[0-9X]$/;
  if (!chinaIDCardRegExp.test(str)) {
    return false;
  }
  // Verify the check digit
  var i,
    lastDigit,
    total = 0;
  var numbers = str.split('');
  for (i = 0; i < 17; i++) {
    total += parseInt(numbers[i], 10) * (Math.pow(2, 17 - i) % 11);
  }
  lastDigit = (12 - (total % 11)) % 11;
  if (lastDigit === 10) {
    lastDigit = 'X';
  }
  if (lastDigit.toString() !== numbers[17].toUpperCase()) {
    return false;
  }
  // Verify the birth date
  var year, month, day, birthday;
  if (numbers.length === 18) {
    year = str.substr(6, 4);
    month = str.substr(10, 2);
    day = str.substr(12, 2);
    birthday = new Date(year, month - 1, day);
    if (
      birthday.getFullYear() != year ||
      birthday.getMonth() + 1 != month ||
      birthday.getDate() != day
    ) {
      return false;
    }
  } else if (numbers.length === 15) {
    year = '19' + str.substr(6, 2);
    month = str.substr(8, 2);
    day = str.substr(10, 2);
    birthday = new Date(year, month - 1, day);
    if (
      birthday.getYear() != year ||
      birthday.getMonth() + 1 != month ||
      birthday.getDate() != day
    ) {
      return false;
    }
  }
  // Verify the Gender
  var gender = parseInt(str.substr(16, 1), 10) % 2 === 1 ? '男' : '女';
  return true;
};

// 判断港澳身份证号码是否有效
export const isHKCard = (str: string) => {
  // 港澳居民来往内地通行证
  // 规则： H/M + 10位或6位数字
  // 样本： H1234567890
  var reg = /^([A-Z]\d{6,10}(\(\w{1}\))?)$/;
  if (reg.test(str) === false) {
    return false;
  } else {
    return true;
  }
};

// 判断护照是否有效
export const isPassPortCard = (str: string) => {
  // 护照
  // 规则： 14/15开头 + 7位数字, G + 8位数字, P + 7位数字, S/D + 7或8位数字,等
  // 样本： 141234567, G12345678, P1234567
  var reg = /^([a-zA-z]|[0-9]){5,17}$/;
  if (reg.test(str) === false) {
    return false;
  } else {
    return true;
  }
};

/** 根据id获取对应的key值 */
export const getKeys = (data, id: string, key: string) => {
  console.log(data, id, key);

  let result = null;
  let fn = function (d) {
    if (Array.isArray(d)) {
      // 判断是否是数组
      for (let i = 0; i < d.length; i++) {
        const e = d[i];
        if (e.id === id) {
          // 数据循环每个子项，并且判断子项下边是否有id值
          result = e[key]; // 返回的结果等于每一项
          break;
        } else if (e.children) {
          fn(e.children); // 递归调用下边的子项
        }
      }
    }
  };
  fn(data); // 调用一下
  return result;
};
